﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace NetworkSimulator
{
    public class Ticker
    {
        private static Ticker singleTonObject = null;
        private Config config = Config.instance();
        private Timer timer;
        private long elapsedTime;

        public long ElapsedTime
        {
            get { return elapsedTime; }
        }

        private int period;
        private List<ITickerListener> listeners;


        public static Ticker instance()
        {
            if (singleTonObject == null)
                singleTonObject = new Ticker();
            return singleTonObject;
        }

        public Ticker()
        {
            listeners = new List<ITickerListener>();
            period = config.PeriodTime;
            elapsedTime = -1;
            timer = new Timer(timerCallBack, null, -1, period);
        }

        public void start()
        {
            timer.Change(elapsedTime + 1, period);
        }

        public void stop()
        {
            timer.Change(-1, period);
        }

        public void addListener(ITickerListener listener)
        {
            listeners.Add(listener);
        }

        private void timerCallBack(Object state)
        {
            elapsedTime++;
            //Console.WriteLine("Tick " + elapsedTime);
            foreach (var listener in listeners)
            {
                listener.onTickerTick();
            }
        }
    }
}
